package com.ja.check.datas;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.context.ContextLoader;

import com.alibaba.druid.util.StringUtils;
import com.ja.check.action.CheckOrder;
import com.ja.check.data.CpData;
import com.ja.domain.Data;
import com.ja.sevice.IDataService;
import com.ja.util.DateUtil;

/**
 * 倒计时开奖时间 当开奖以后不管是否已经开奖 更新开奖状态
 * @author Administrator
 *
 */
public class OpenData {
	
	private IDataService dataService = (IDataService) ContextLoader.getCurrentWebApplicationContext()
			.getBean("dataService");	
	public static Map<String, Data> isShotFlags = Collections.synchronizedMap(new HashMap<String, Data>());
	/**
	 * 初始化当前未开奖的最新一期数据集合
	 */
	public void startReviewTask() {
		List<Data> data = dataService.findCurrDatas(DateUtil.formatDateTime(LocalDateTime.now()));
		System.out.println(data);
		if(data == null || data.size() <= 0) {
			new Integer("数据库数据为空");
		}
		for (int i = 0; i < data.size(); i++) {
			Data d = data.get(i);
			isShotFlags.put(d.getCname(),d);
			startReviewThread(d.getCname());
		}
	}
	/**
	 * 倒计时当前开奖的一期数据      然后在倒计时下一期   当当期开奖时间到了以后 就修改成1  然后在继续倒计时下期在条数据的下一期  如果下期的时间到了  但是当期的还没有开出来 那就更新成异常数据
	 */
	public void startReviewThread(String cname) {
		new Thread(new Runnable() {
			public void run() {
				while(true) {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Long endTime = sdf.parse(isShotFlags.get(cname).getOpenTime()).getTime();
						//当前系统时间
						Long startTime = sdf.parse(sdf.format(new Date())).getTime();
						if(endTime - startTime > 0) {	
							Thread.sleep(endTime - startTime);
						}
						dataService.updataCnameStatus(cname, isShotFlags.get(cname).getPeriod());
						Long nextEndTime = sdf.parse(isShotFlags.get(cname).getNextStopOrderTimeEpoch()).getTime();
						//当前系统时间
						Long nextStartTime = sdf.parse(sdf.format(new Date())).getTime();
						if(nextEndTime - nextStartTime - 30  > 0) {		
							Thread.sleep(nextEndTime - nextStartTime - 30);
						}
						Data currData = dataService.findById(isShotFlags.get(cname).getId());
						if (currData !=null && StringUtils.isEmpty(currData.getLotternumber())) {
							CpData.isShotFlags.put(currData.getCname(), currData.getNextperiod());
							dataService.updateLotterNumberToEmptyStr(currData.getId());
							new CheckOrder().checkLotters(currData);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}finally {
						Data nextData = dataService.findDataByNameAndPeriod(cname, isShotFlags.get(cname).getNextperiod());
						isShotFlags.put(cname, nextData);
					}
				}
			}
		}).start();
	}
	
}
